package com.hunantv.mglive.ui.live;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseFragment;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.data.GiftDataModel;
import com.hunantv.mglive.data.GiftNumModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.live.ChatData;
import com.hunantv.mglive.ui.entertainer.data.ContributionInfoData;
import com.hunantv.mglive.utils.MGLiveMoneyUtil;
import com.hunantv.mglive.utils.RoleUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.Toast.ConfirmDialog;

/**
 * Created by qiuda on 16/3/26.
 */
public class StarLiveInputFragment extends BaseFragment implements View.OnKeyListener {
    private boolean isYell;
    private String mStarId;
    private String mStarName;
    private View mVChatInput;
    private EditText mEdtInput;
    private TextView mSendChatBtn;
    private View mShoutSwitch;
    private ImageView mShoutImg;
    private GiftDataModel mYellGifData;
    private ContributionInfoData mContributionInfo;
    private IinputViewCallBack mCallback;
    private InputMethodManager mImm;
    private ConfirmDialog mConfirmDialog;
    private OnSendContentListener mContentListener;
    private ChatData chatTmp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mVChatInput = LayoutInflater.from(getContext()).inflate(R.layout.star_live_input_layout, null);
        mEdtInput = (EditText) mVChatInput.findViewById(R.id.edt_starlive_chat_inputChatText);
        mEdtInput.requestFocus();
        mEdtInput.requestFocusFromTouch();
        mEdtInput.setOnKeyListener(this);
        mShoutSwitch = mVChatInput.findViewById(R.id.fl_star_live_chat_shout);
        mShoutImg = (ImageView) mVChatInput.findViewById(R.id.ib_star_live_chat_shout);

        mSendChatBtn = (TextView) mVChatInput.findViewById(R.id.tv_star_live_chat_sendChatBtn);
        mVChatInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInputView();
            }
        });
        initChatView();
        initDialog();
        setEditTextHint();
        mImm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
        return mVChatInput;
    }

    /**
     * 初始化聊天区域
     */
    private void initChatView() {
        //发送按钮
        mSendChatBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMsg();
            }
        });
        //喊话滑块
        //聊天喊话滑块
        mShoutSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mYellGifData == null)
                    return;
                if (isYell) {
                    mEdtInput.setHint(getActivity().getString(R.string.star_live_input_msg));
                    mShoutImg.setSelected(false);
                    isYell = false;
                } else {
                    if (mContributionInfo != null && !ContributionInfoData.GRADE_LEVEL_NO.equals(mContributionInfo.getGradeName())) {
                        mEdtInput.setHint(getActivity().getString(R.string.live_send_msg_vip));
                    } else {
                        mEdtInput.setHint(getActivity().getString(R.string.live_send_msg, mYellGifData.getPrice() + ""));
                    }
                    mShoutImg.setSelected(true);
                    isYell = true;
                }
            }
        });
    }

    private void initDialog(){
        mConfirmDialog = new ConfirmDialog(getContext(), R.string.tips_not_gold, R.string.ok_1, R.string.cancel);
        mConfirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {

                MGLiveMoneyUtil.getInstance().goMGLiveMonneyPay(getActivity());

                mConfirmDialog.dismiss();
            }

            @Override
            public void doCancel() {
                mConfirmDialog.cancel();
            }
        });
    }

    public void setEditTextHint() {
        if (mEdtInput != null && mShoutSwitch != null) {
            if (mYellGifData != null) {
                if (mContributionInfo != null && !ContributionInfoData.GRADE_LEVEL_NO.equals(mContributionInfo.getGradeName())) {
                    mEdtInput.setHint(getActivity().getString(R.string.live_send_msg_vip));
                } else {
                    mEdtInput.setHint(getActivity().getString(R.string.live_send_msg, mYellGifData.getPrice() + ""));
                }
                mShoutSwitch.setVisibility(View.VISIBLE);
            }
        }
    }

    private void sendMsg() {
        if (!isLogin()) {
            jumpToLogin("登录以后才可以发消息哦~");
            return;
        }
        if (!StringUtil.isNullorEmpty(getMqttClientId())) {
            String chatText = mEdtInput.getText().toString();
            if(!StringUtil.isNullorEmpty(chatText))
            {
                if (isYell) {
                    if (mYellGifData != null) {
                        sendGrund(chatText, mYellGifData);
                    }
                } else {
                    sendChatContent(chatText);
                    mEdtInput.setText("");
                    hideInputView();
                }
            }else
            {
                hideInputView();
            }
        }
    }

    private void updateSendChatEditTextView() {
        if (mYellGifData != null) {
            mEdtInput.setHint(getActivity().getString(R.string.star_live_input_msg));
        }
    }

    /**
     * 发送聊天内容
     *
     * @param chatStr
     */
    private void sendChatContent(String chatStr) {
        sendMqttMsg(ChatData.CHAT_TYPE_CONTENT, chatStr, null, null);
    }

    /**
     * 发送喊话
     * @param chatStr
     * @param giftData
     */
    private void sendGrund(String chatStr, GiftDataModel giftData) {
        sendMqttMsg(ChatData.CHAT_TYPE_GIFT, chatStr, giftData, new GiftNumModel(1));
    }

    /**
     * 发送mqtt消息
     * @param type
     * @param chatStr
     * @param giftData
     * @param giftNum
     */
    private void sendMqttMsg(int type,String chatStr,GiftDataModel giftData,GiftNumModel giftNum) {
        //消费礼物
        ChatData chatData = new ChatData();
        chatData.setType(type);
        if (isLogin() && getUserInfo() != null) {
            chatData.setUuid(getUid());
            chatData.setNickname(getUserInfo().getNickName());
            chatData.setAvatar(getUserInfo().getPhoto());
        }

        if (ChatData.CHAT_TYPE_VIP_JOIN_IN == type || ChatData.CHAT_TYPE_CONTENT == type) {
            chatData.setBarrageContent(chatStr);
        }

        if (type == ChatData.CHAT_TYPE_GIFT) {
            sendGift(chatStr,giftData, giftNum);
        } else {
            sendMqttChat(chatData);
        }
    }

    /**
     * 发送普通聊天内容
     * @param chatData
     */
    private void sendMqttChat(ChatData chatData) {
        FormEncodingBuilderEx build = new FormEncodingBuilderEx();
        build.add("uid", getUid());
        build.add("token", getToken());
        build.add("flag", getMqttFlag());
        build.add("key", getMqttKey());
        build.add("clientId", getMqttClientId());
        build.add("tip", chatData.getBarrageContent());
        build.add("content", chatData.getBarrageContent());
        build.add("title", mStarName + "-个人直播间");
        build.add("artistIds", mStarId);
        build.add("grade", (mContributionInfo != null && !StringUtil.isNullorEmpty(mContributionInfo.getGradeLevel())) ?  mContributionInfo.getGradeLevel() : "0" );
        post(BuildConfig.CHAT_SEND_PATH_V2, build.build());
        chatTmp = chatData;
    }

    /**
     * 发送礼物消息
     */
    private void sendGift(String chatStr,GiftDataModel giftData,GiftNumModel giftNum){
        FormEncodingBuilderEx builder = new FormEncodingBuilderEx();
        builder.add("gid", giftData.getGid() + "");
        builder.add("count", giftNum.getGiftNum() + "");
        builder.add("gift", StringUtil.isNullorEmpty(chatStr) ? "1" : "2");
        builder.add("amount", giftNum.getGiftNum() * giftData.getPrice() + "");
        builder.add("buid", getUid());
        builder.add("cuid", mStarId);
        builder.add("token", getToken());
        builder.add("tip", StringUtil.isNullorEmpty(chatStr) ? "送给 " + mStarName : chatStr);
        if (!StringUtil.isNullorEmpty(getMqttClientId())) {
            builder.add("clientId", getMqttClientId());
            builder.add("flag", getMqttFlag());
            builder.add("key", getMqttKey());
        }
        post(BuildConfig.PAY_GIFT, builder.build());
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        return super.asyncExecute(url, resultModel);
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) {
        super.onSucceed(url, resultModel);
        if (BuildConfig.PAY_GIFT.equals(url)) {
            mEdtInput.setText("");
            hideInputView();
        } else if (BuildConfig.CHAT_SEND_PATH_V2.equals(url)) {
            //自己发送的消息显示
            //本地显示自己的消息需重新处理role与grade
            if(chatTmp != null)
            {
                if(mContributionInfo != null && !StringUtil.isNullorEmpty(mContributionInfo.getGradeLevel())){
                    chatTmp.setGrade(Integer.parseInt(mContributionInfo.getGradeLevel()));
                }else
                {
                    chatTmp.setGrade(0);
                }
                if(isLogin() && getUserInfo() != null)
                {
                    chatTmp.setRole(getUserInfo().getRole());
                }else
                {
                    chatTmp.setRole(RoleUtil.ROLE_PT);
                }
                if(mContentListener != null) {
                    mContentListener.sendContent(chatTmp);
                }
            }
            chatTmp = null;
        }
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        super.onFailure(url, resultModel);
        if (BuildConfig.PAY_GIFT.equals(url)) {
            if ("2201".equals(resultModel.getCode()) || resultModel.getMsg().startsWith("剩余金币不足")) {
                if (!mConfirmDialog.isShowing()) {
                    mConfirmDialog.show();
                }
            }
        } else if (BuildConfig.GET_CONTRIBUTION_INFO.equals(url)) {
            //守护信息
            mContributionInfo = null;
        } else if (!"200".equals(resultModel.getCode()) && !"10".equals(resultModel.getCode())) {//敏感信息不提示
            if (BuildConfig.CHAT_SEND_PATH_V2.equals(url)) {
                chatTmp = null;
            }
            Toast.makeText(getContext(), resultModel.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onError(String url, Exception e) {
        if (BuildConfig.CHAT_SEND_PATH_V2.equals(url)) {
            chatTmp = null;
        }
        super.onError(url, e);
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER && mVChatInput.getVisibility() == View.VISIBLE) {
            sendMsg();
            return true;
        }
        return false;
    }

    public void setStarInfo(String starid, String starName) {
        mStarId = starid;
        mStarName = starName;
    }

    public void setGiftData(GiftDataModel yellGifData) {
        mYellGifData = yellGifData;
        updateSendChatEditTextView();
    }

    public void setContributionInfoData(ContributionInfoData contributionInfoData) {
        mContributionInfo = contributionInfoData;
        setEditTextHint();
    }

    public void setInputCallBack(IinputViewCallBack callback) {
        mCallback = callback;
    }

    public void showInputView(String mContent) {
        mEdtInput.requestFocus();
        if (!StringUtil.isNullorEmpty(mContent)) {
            mEdtInput.setText(mContent);
            mEdtInput.setSelection(mContent.length());
        }
        mImm.showSoftInput(mEdtInput, 0);
        mVChatInput.setVisibility(View.VISIBLE);
    }

    public void hideInputView() {
        if (mCallback != null) {
            mCallback.hasSend();
        }

        mImm.hideSoftInputFromWindow(mEdtInput.getWindowToken(), 0);
        mVChatInput.setVisibility(View.GONE);
    }

    public boolean onBackpressed() {
        if (mVChatInput.getVisibility() == View.VISIBLE) {
            hideInputView();
            return true;
        } else {
            return false;
        }
    }

    public interface IinputViewCallBack {
        void hasSend();
    }

    public void setContentListener(OnSendContentListener mContentListener) {
        this.mContentListener = mContentListener;
    }

    /**
     * 发送聊天回调
     */
    public interface OnSendContentListener{
        public void sendContent(ChatData chatdata);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mCallback = null;
        mContentListener = null;
    }
}